package cn.com.zero.manager.auth.service.impl;

import cn.com.zero.api.auth.util.UserCacheKeyUtil;
import cn.com.zero.base.service.BaseService;
import cn.com.zero.base.util.RedisUtil;
import cn.com.zero.manager.auth.api.constant.TokenKeyConstant;
import cn.com.zero.manager.auth.constant.AuthConstant;
import cn.com.zero.manager.auth.enums.LoginClientEnum;
import cn.com.zero.manager.auth.mapper.IManageOnlineMapper;
import cn.com.zero.manager.auth.service.IManageOnlineService;
import cn.com.zero.manager.auth.vo.OnlineManagerVO;
import cn.com.zero.manager.auth.vo.OnlineVerificationTimeVO;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author guoxin
 * @version 1.0.0
 * @Description
 * @date 2023/3/2 11:36
 */
@Service
public class ManageOnlineService extends BaseService implements IManageOnlineService {

    /**
     * Redis工具类
     */
    private RedisUtil redisUtil;

    /**
     * 对称加密密钥
     */
    @Value(TokenKeyConstant.SECUREKEY)
    private String secureUtilKey;

    private IManageOnlineMapper manageOnlineMapper;

    /**
     * 查询在线管理员
     *
     * @param userId            用户编号
     * @param nickname          名称
     * @param showMobilePhone   手机号
     * @param beginTime         开始时间
     * @param endTime           结束时间
     * @param loginClient       登录设备
     * @return
     */
    @Override
    public List<OnlineManagerVO> queryOnlineCustomer(String userId, String nickname, String showMobilePhone,
                                                     Date beginTime, Date endTime, Integer loginClient) {
        if(null == loginClient){
            loginClient = LoginClientEnum.PC_WEB.getValue();
        }
        //获取在线用户的id和登录设备
        Set<String> keys = redisUtil.keys(UserCacheKeyUtil.getOnlineUserCacheKey(AuthConstant.MANAGER,LoginClientEnum.getValueByName(loginClient),null));
        //存放在线用户id的集合
        ArrayList<String> userIds = new ArrayList<>();
        //初始化集合，防止用集合查询数据库时sql语句报错
        userIds.add("");
        //存放在线用户登录时间信息集合
        Map<String, OnlineVerificationTimeVO> stringOnlineVerificationTimeVOMap = new HashMap<>();
        //从redis中获取存放在线用户登录时间信息
        for(String key : keys){
            String online = (String)redisUtil.getObject(key);
            OnlineVerificationTimeVO onlineVerificationTimeVO = JSONObject.parseObject(online, OnlineVerificationTimeVO.class);
            if(null != beginTime && null != endTime){
                if(!(beginTime.compareTo(onlineVerificationTimeVO.getCreateTime())<=0 && endTime.compareTo(onlineVerificationTimeVO.getCreateTime())>=0)){
                    continue;
                }
            }
            stringOnlineVerificationTimeVOMap.put(onlineVerificationTimeVO.getUserID(),onlineVerificationTimeVO);
            userIds.add(onlineVerificationTimeVO.getUserID());
        }
        //如果查询电话条件不为空，先加密
        String encrypt = "";
        if (!StringUtils.isBlank(showMobilePhone)){
            encrypt = SecureUtil.aes(secureUtilKey.getBytes()).encryptHex(showMobilePhone);
        }
        //数据库查询用户
        List<OnlineManagerVO> onlineManagerVOList = manageOnlineMapper.selectOnlineManagers(userId, nickname, encrypt, userIds);
        if(!CollectionUtil.isEmpty(onlineManagerVOList))
        onlineManagerVOList.forEach(O->{
            O.setLoginClient(stringOnlineVerificationTimeVOMap.get(O.getUserID()).getLoginClient());
            O.setLoginIp(stringOnlineVerificationTimeVOMap.get(O.getUserID()).getLoginIp());
            O.setCreateTime(stringOnlineVerificationTimeVOMap.get(O.getUserID()).getCreateTime());
            O.setLoginHour(String.valueOf((System.currentTimeMillis() - O.getCreateTime().getTime())/3600000));
            O.setLoginMin(String.valueOf(((System.currentTimeMillis() - O.getCreateTime().getTime())/60000) -
                    (Long.valueOf(O.getLoginHour()) * 60)));
        });
        return onlineManagerVOList;
    }

    /**
     * 下线管理员
     *
     * @param userId        用户编号
     * @param loginClient   登录设备
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean kickoff(String userId, Integer loginClient) {
        if(null != redisUtil.getObject(UserCacheKeyUtil.getOnlineUserCacheKey(AuthConstant.MANAGER,LoginClientEnum.getValueByName(loginClient),userId))){
            redisUtil.delete(UserCacheKeyUtil.getMenuPermissionCacheKey(AuthConstant.MANAGER,LoginClientEnum.getValueByName(loginClient),userId),
                    UserCacheKeyUtil.getOnlineUserCacheKey(AuthConstant.MANAGER,LoginClientEnum.getValueByName(loginClient),userId));
            return true;
        }
        return false;
    }

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Autowired
    public void setManageOnlineMapper(IManageOnlineMapper manageOnlineMapper) {
        this.manageOnlineMapper = manageOnlineMapper;
    }
}
